package com.example.musicplayer.model;
import java.util.*;


import android.media.*;

import com.example.musicplayer.myinterface.ICompletionObserver;
import com.example.musicplayer.myinterface.IObservable;
import com.example.musicplayer.myinterface.IViewObserver;

public class Video extends Media implements IObservable
{

	private ArrayList<IViewObserver> viewObservers=new ArrayList();//视图观察者集合
	private ArrayList<ICompletionObserver> controllerObservers=new ArrayList();//播放完成观察者集合
	private static Video video;//视频对象
	
	@Override
	public void registerViewObserver(IViewObserver observer)
	{
		viewObservers.add(observer);
	}

	@Override
	public void removeViewObserver(IViewObserver observer)
	{
		viewObservers.remove(observer);
	}

	@Override
	public void notifyViewObservers()
	{
		for(IViewObserver o:viewObservers){
			o.update();
		}
	}

	@Override
	public void registerCompletionObserver(ICompletionObserver observer)
	{
		controllerObservers.add(observer);
	}

	@Override
	public void removeCompletionObserver(ICompletionObserver observer)
	{
		controllerObservers.remove(observer);
	}

	@Override
	public void notifyCompletionObservers()
	{
		for(ICompletionObserver o:controllerObservers){
			o.updateCompletion();
		}
	}


	/**
	 * 构造函数初始化参数
	 */
	private Video(){
		completion();
		new NotifyThread().start();
	}
	
	//采用单一模式获取Video对象
	public static synchronized Video getInstance(){
		if(video==null){
			video=new Video();
		}
		return video;
	}


	/**
	 * 播放完成监听
	 */
	public void completion(){
		this.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){

				@Override
				public void onCompletion(MediaPlayer p1)
				{
					notifyCompletionObservers();
				}
			});
	}
	
	/**
	 * 定时更新界面类
	 * @author hyh
	 *
	 */
	class NotifyThread extends Thread
	{
		@Override
		public void run()
		{
			while(true){
				try
				{
					notifyViewObservers();
					Thread.sleep(500);
				}
				catch (InterruptedException e)
				{}
			}
		}
	}
	
	
}
